
$(document).ready(function(){
	var curMenu = null, zTree_Menu = null;
	initLayout();
	bindEvent();
	initdialog ();
	inittreeNav();
	initTab($.fn.zTree.getZTreeObj("treeDemo").getSelectedNodes()[0]);
})

/************** Layout start *****************/

function initLayout(){
	// create the OUTER LAYOUT
	//initToolbar();
	var outerLayout, innerLayout;
	outerLayout = $("body").layout(layoutSettings_Outer);
	/*******************************
	 *** CUSTOM LAYOUT BUTTONS ***
	 *******************************
	 *
	 * Add SPANs to the east/west panes for customer "close" and "pin" buttons
	 *
	 * COULD have hard-coded span, div, button, image, or any element to use as a 'button'...
	 * ... but instead am adding SPANs via script - THEN attaching the layout-events to them
	 *
	 * CSS will size and position the spans, as well as set the background-images
	 */
	// BIND events to hard-coded buttons in the NORTH toolbar
	//outerLayout.addToggleBtn("#tbarToggleNorth", "north");
	//outerLayout.addOpenBtn("#tbarOpenSouth", "south");
	//outerLayout.addPinBtn("#tbarPinWest", "west");
	//outerLayout.addPinBtn("#tbarPinEast", "east");
	// save selector strings to vars so we don't have to repeat it
	// must prefix paneClass with "body > " to target ONLY the outerLayout panes
	var westSelector = "body > .ui-layout-west"; // outer-west pane
	var eastSelector = "body > .ui-layout-east"; // outer-east pane
	// CREATE SPANs for pin-buttons - using a generic class as identifiers
	//$("<span></span>").addClass("pin-button").prependTo(westSelector);
	//$("<span></span>").addClass("pin-button").prependTo(eastSelector);
	// BIND events to pin-buttons to make them functional
	//outerLayout.addPinBtn(westSelector + " .pin-button","west");
	//outerLayout.addPinBtn(eastSelector + " .pin-button","east");
	// CREATE SPANs for close-buttons - using unique IDs as identifiers
	$("<span></span>").attr("id", "west-closer").prependTo(westSelector);
	$("<span></span>").attr("id", "east-closer").prependTo(eastSelector);
	// BIND layout events to close-buttons to make them functional
	outerLayout.addCloseBtn("#west-closer", "west");
	outerLayout.addCloseBtn("#east-closer", "east");
	/* Create the INNER LAYOUT - nested inside the 'center pane' of the outer layout
	 * Inner Layout is create by createInnerLayout() function - on demand
	 *
	 innerLayout = $("div.pane-center").layout( layoutSettings_Inner );
	 *
	 */
	// DEMO HELPER: prevent hyperlinks from reloading page when a 'base.href' is set
	$("a").each(function() {
		var path = document.location.href;
		if (path.substr(path.length - 1) == "#")
			path = path.substr(0, path.length - 1);
		if (this.href.substr(this.href.length - 1) == "#")
			this.href = path + "#";
	});
}

/*
			 *#######################
			 * OUTER LAYOUT SETTINGS
			 *#######################
			 *
			 * This configuration illustrates how extensively the layout can be customized
			 * ALL SETTINGS ARE OPTIONAL - and there are more available than shown below
			 *
			 * These settings are set in 'sub-key format' - ALL data must be in a nested data-structures
			 * All default settings (applied to all panes) go inside the defaults:{} key
			 * Pane-specific settings go inside their keys: north:{}, south:{}, center:{}, etc
			 */
var layoutSettings_Outer = {
				name : "outerLayout" // NO FUNCTIONAL USE, but could be used by custom code to 'identify' a layout
				// options.defaults apply to ALL PANES - but overridden by pane-specific settings
				,
				defaults : {
					size : "auto",
					minSize : 30,
					paneClass : "pane" // default = 'ui-layout-pane'
					,
					resizerClass : "resizer" // default = 'ui-layout-resizer'
					,
					togglerClass : "toggler" // default = 'ui-layout-toggler'
					,
					buttonClass : "button" // default = 'ui-layout-button'
					,
					contentSelector : ".content" // inner div to auto-size so only it scrolls, not the entire pane!
					,
					contentIgnoreSelector : "span" // 'paneSelector' for content to 'ignore' when measuring room for content
					,
					togglerLength_open : 35 // WIDTH of toggler on north/south edges - HEIGHT on east/west edges
					,
					togglerLength_closed : 35 // "100%" OR -1 = full height
					,
					hideTogglerOnSlide : true // hide the toggler when pane is 'slid open'
					,
					togglerTip_open : "Close This Pane",
					togglerTip_closed : "Open This Pane",
					resizerTip : "Resize This Pane"
					// effect defaults - overridden on some panes
					,
					fxName : "slide" // none, slide, drop, scale
					,
					fxSpeed_open : 750,
					fxSpeed_close : 1500,
					fxSettings_open : {
						easing : "easeInQuint"
					},
					fxSettings_close : {
						easing : "easeOutQuint"
					}
				},
				north : {
					spacing_open : 1 // cosmetic spacing
					,
					togglerLength_open : 0 // HIDE the toggler button
					,
					togglerLength_closed : -1 // "100%" OR -1 = full width of pane
					,
					resizable : false
					, 
					slidable: false
					,
				// override default effect
				   fxName: "none",
				}, 
				south: {
					maxSize : 55,
					size : 40,
					spacing_closed : 5 // HIDE resizer & toggler when 'closed'
					,
					spacing_open : 3,
					slidable : false // REFERENCE - cannot slide if spacing_closed = 0
					,
					initClosed : true,
					resizable : false, 
				},
				west : {
					spacing_open : 3
					,
					size : 215,
					spacing_closed : 21 // wider space when closed
					,
					togglerLength_closed : 21 // make toggler 'square' - 21x21
					,
					togglerAlign_closed : "top" // align to top of resizer
					,
					togglerLength_open : 0 // NONE - using custom togglers INSIDE west-pane
					,
					//togglerTip_open : "Close West Pane",
					//togglerTip_closed : "Open West Pane",
					//resizerTip_open : "Resize West Pane",
					slideTrigger_open : "click" // default
					,
					resizable : false, 
					initClosed : false
					// add 'bounce' option to default 'slide' effect
					,
					/*fxSettings_open : {
						easing : "easeOutBounce"
					}*/
				},
				east : {
					spacing_open : 3
					,
					size : 250,
					spacing_closed : 21 // wider space when closed
					,
					togglerLength_closed : 21 // make toggler 'square' - 21x21
					,
					togglerAlign_closed : "top" // align to top of resizer
					,
					togglerLength_open : 0 // NONE - using custom togglers INSIDE east-pane
					,
					togglerTip_open : "Close East Pane",
					togglerTip_closed : "Open East Pane",
					resizerTip_open : "Resize East Pane",
					slideTrigger_open : "click",
					resizable : false, 
					initClosed : true
					// override default effect, speed, and settings
					,
					initHidden : true,
					fxName : "drop",
					fxSpeed : "normal",
					fxSettings : {
						easing : ""
					}
				// nullify default easing
				},
				center : {
					paneSelector : "#mainContent" // sample: use an ID to select pane instead of a class
					,
					minWidth : 200,
					minHeight : 200
				}
			};

/************** Layout end *****************/

/************** Nav Tree start *****************/
function beforeNavItemClick(treeId, node) {
	if (node.isParent) {
		if (node.level === 0) {
			var pNode = curMenu;
			while (pNode && pNode.level !==0) {
				pNode = pNode.getParentNode();
			}
			if (pNode !== node) {
				var a = $("#" + pNode.tId + "_a");
				a.removeClass("cur");
				zTree_Menu.expandNode(pNode, false);
			}
			a = $("#" + node.tId + "_a");
			a.addClass("cur");

			var isOpen = false;
			for (var i=0,l=node.nodes.length; i<l; i++) {
				if(node.nodes[i].open) {
					isOpen = true;
					break;
				}
			}
			if (isOpen) {
				zTree_Menu.expandNode(node, true);
				curMenu = node;
			} else {
				zTree_Menu.expandNode(node.nodes[0].isParent?node.nodes[0]:node, true);
				curMenu = node.nodes[0];
			}
		} else {
			zTree_Menu.expandNode(node);
		}
	}
		
	return !node.isParent;
}
function onNavItemClick(e, treeId, node) {
	
	if(node.handler){
		node.handler();
	}else{
		openTab(node);
	}
}



function inittreeNav() {
	var zNodes = treedetail;
	var setting = {
	view: {
		showLine: true,
		selectedMulti: false,
		dblClickExpand: false,
		autoOpen:false,
	},
	data: {
	key: {
		children: "nodes",
		name: "name",
		title: "",
		url: "url"
	},
		simpleData: {
			enable: true
		}
	},
	callback: {
		onNodeCreated: this.onNodeCreated,
		beforeClick: beforeNavItemClick,
		onClick: onNavItemClick
	},
};

	$.fn.zTree.init($("#treeDemo"), setting, zNodes);
	zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo");
	curMenu = zTree_Menu.getNodes()[0];
	
	if(curMenu){
		while (curMenu.isParent) {
					curMenu = curMenu.nodes[0];
		}
	}
	if(!zTree_Menu.getNodes()[0]){
		return;
	}
	zTree_Menu.expandNode(zTree_Menu.getNodes()[0], true);
	
	zTree_Menu.selectNode(curMenu);
	//openTab(zTree_Menu.getSelectedNodes()[0]);
	var a = $("#" + zTree_Menu.getNodes()[0].tId + "_a");
	a.addClass("cur");
}


function openTab(node){
  updateTopoTree(false, node.code);
  
  if(node.id == 11001){
	  $( ".about" ).dialog( "open" );
	  return;
  }
  tabpanel.addTab({id: node.code, title:node.name, html:'<iframe id="'+"iframe_"+node.code+'"src="'+baserUrl+node.url+'" width="100%" height="100%" frameborder="0"></iframe>', handler: updateTopoTree, closeHandler: updateTopoTree});
  tabpanel.resize();
}
		
function updateTopoTree(isClose, tabId)
{
	if(tabId == 11001){
	  return;
  }
  var layout = $('body').layout();

  if(!isClose && tabId == 1001 && layout.state.east.isHidden)
  {
	 layout.show('east', false);
	 

  }else if(isClose && !layout.state.east.isHidden || !isClose && !layout.state.east.isHidden && tabId != 1001){
	  layout.hide("east");
	   var layout = $('body').layout();
	  layout.resizeAll();
  }
}


function initTab(node){
	//updateTopoTree(false,node.code);
	  tabpanel = new TabPanel({
		renderTo:'tab',
		autoResizable:true,
		border:'none',
		active : 0,
		maxLength : 30,
		items : []
	});
	  openTab(node);
	  
}
/************** Nav Tree end *****************/



function initToolbar(){
	var toolbar;
	toolbar = new Toolbar({
        renderTo : 'toolbar',
        items : [{
          type : 'button',
          text : '点击添加选项卡(此区域放置快捷方式)',
          bodyStyle : 'new',
          useable : 'T',
          handler : function(){
            //addmenu();
           // tabpanel.resize();
          }
        }]
      });

	  toolbar.render();
	  
}


function bindEvent(){
	$('#password').click(function() {
    	changePassword();
	});
	$('#west-closer').click(function() {
    	tabpanel.resize();
	});
	$('#east-closer').click(function() {
    	tabpanel.resize();
	});
	$('.toggler-east-closed').click(function() {
    	tabpanel.resize();
    	//$('iframe').attr('src',$("iframe").attr('src'));
	});
	
	
	
	/*$('#logout').click(function() {
    	logOut();
	});*/
}
function changePassword(){
	$( ".changePassword" ).dialog( "open" );
}

function logOut(){
	$( ".logoutDialog" ).dialog( "open" );
}

function initdialog (){
	$( ".changePassword" ).dialog({
		autoOpen: false,
		height: 200,
		width: 500,
		modal: true,
		buttons: {
			"确认": function() {
				submitPasspword();
			},
			"取消": function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
		}
	});
	$( ".about" ).dialog({
		autoOpen: false,
		height: 180,
		width: 380,
		modal: true,
		buttons: {
			"关闭": function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
		}
	});
	
	$( ".logoutDialog" ).dialog({
		autoOpen: false,
		height: 200,
		width: 500,
		modal: true,
		buttons: {
			"确认": function() {
			$.post(baserUrl+'logout', "");
			
			},
			"取消": function() {
				
			}
		},
		close: function() {
		}
	});
}

function submitPasspword(){
	if(!$("#pwdForm").valid()){
				return;
	}
	$.adAjax({
			type : "post",
			url:baserUrl+'user/changePassword',
			data:$('#pwdForm').serialize(),
			success : function(){
				$( ".changePassword" ).dialog( "close" );
			}
		});
}
